<?php
namespace app\admin\controller;
use app\common\model\Orders;
use app\common\model\OrdersItem;
use app\common\model\Goods;
use app\common\model\Purchase;
use app\common\model\ExpressItem;
use think\Validate;
use think\Db;
use think\Session;
use app\admin\library\orders\LibraryOrders;
use app\common\model\ProjectLog;
use app\admin\library\rules\Rules;
use Exception;
use think\worker\Server;
use app\common\model\Account;

class OrdersController extends BaseController
{
    public function _initialize(){
        $this->project_log_model = new ProjectLog();
        $this->cancel_model = new \app\common\model\OrdersItemCancel;
        $this->reject_model = new \app\common\model\OrdersItemReject();
    }
    public function lists()
    {
        return view();
    }
    public function lists2()
    {
        return view();
    }
    public function getList()
    {
        // 获取团队
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        
        
        $where = $this->buildParams();
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            unset($where['date1']);
            unset($where['date2']);
        }else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where['o.add_time'] = ['between',[$date1, $date2]];
        
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
        }
        // 检查当前用户是否有查询全部订单权限(true)，否则只能查询3个月内的订单(false)
        // $rules = Rules::hasRules(2);
        // if(!$rules){
        //     $time = time()-3*30*24*60*60;
        //     $where['o.add_time'] = ['>',$time];
        // }
        $account = Db::name('account')->where('id',$account_id)->find();
        // 只查看自己的订单
        if($account['order_status'] == 1){
            $where['o.acct_id'] = $account_id;
        }
        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Db::name('orders')
                    ->alias('o')
                    ->join('__ORDERS_ITEM__ oi', 'o.id = oi.order_id')
                    ->join('__GOODS__ g', 'oi.goods_id = g.id')
                    ->group('order_id')
                    ->where($where)
                    ->count();
        $rows = Db::name('orders')
                    ->alias('o')
                    ->join('__ORDERS_ITEM__ oi', 'o.id = oi.order_id')
                    ->join('__GOODS__ g', 'oi.goods_id = g.id')
                    ->field('o.id,order_no,cust,phone,area_path,detail_addr,pay_type,recv_day,o.add_time,o.acct_id,GROUP_CONCAT(oi.id) as oi_ids')
                    ->order('o.add_time DESC')
                    ->group('order_id')
                    ->where($where)
                    ->page($page, $page_size)
                    ->select();
        
        // 有到货的要显示全部子订单
        if(isset($where['progress']) && $where['progress'] == 3){
            foreach ($rows as &$value) {
                $oi_ids = Db::name('orders_item')->where('order_id', $value['id'])->column('id');
                $value['oi_ids'] = implode(',',$oi_ids);
            }
        }

        $item_map = $this->getItemsMap($rows);
        //acct信息
        $acct_map = Db::name('account')->where('id', 'in', array_column($rows, 'acct_id'))
                                    ->column('');

        $pay_types = Orders::$pay_types;
        
        foreach ($rows as &$row) {
            $row['pay_type'] = $pay_types[$row['pay_type']];
            $row['acct_name'] = $acct_map[$row['acct_id']]['true_name'];
             // 订单未发货
            $is_over_time = ((time() - $row['add_time'])/3600)>48;
            $row['add_day'] = date('Y-m-d', $row['add_time']);
            $row['add_time'] = date('H:i', $row['add_time']);
            $oi_ids = $row['oi_ids'];
            $oi_ids = explode(',', $oi_ids);
            $row['items'] = [];

            // 添加物流订单号
            $oi_ids = explode(',', $row['oi_ids']);
            $express = Db::name('express_item')
                    ->alias('ei')
                    ->join('__EXPRESS__ e', 'e.id = ei.express_id')
                    ->where('order_item_id',$oi_ids[0])
                    ->find();
            if(!empty($express)){
                $row['express_no'] = $express['express_no'];
            }else{
                $row['express_no'] = null;
            }
            $row['over_time'] = false;
            foreach ($oi_ids as $oi_id) {
                $row['items'][] = $item_map[$oi_id];
                if(in_array($item_map[$oi_id]['progress'],[1,2,3])&&$is_over_time){
                    $row['over_time'] = true;
                }
            }
            $row['can_ship'] = array_sum(array_column($row['items'], 'can_ship'));
        }

        $all_data = $this->allData($where);

        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page,
            'all_data' => $all_data
        ];

        $this->success('获取成功','',$data);
        
    }
    /**
     * 计算订单列表的总金额和商品数量
     */
    protected function allData($where){

        $data = [
            'all_price' => 0,
            'all_qty' => 0
        ];
        try {
            $rows = Db::name('orders')
                    ->alias('o')
                    ->join('__ORDERS_ITEM__ oi', 'o.id = oi.order_id')
                    ->join('__GOODS__ g', 'oi.goods_id = g.id')
                    ->field('o.id,order_no,cust,phone,area_path,detail_addr,pay_type,recv_day,o.add_time,o.acct_id,GROUP_CONCAT(oi.id) as oi_ids')
                    ->order('o.add_time DESC')
                    ->group('order_id')
                    ->where($where)
                    ->select();
            // return $data;
            // 有到货的要显示全部子订单
            if(isset($where['progress']) && $where['progress'] == 3){
                foreach ($rows as &$value) {
                    $oi_ids = Db::name('orders_item')->where('order_id', $value['id'])->column('id');
                    $value['oi_ids'] = implode(',',$oi_ids);
                }
            }
            $item_map = $this->getItemsMap($rows);
            foreach ($rows as &$row) {
                $oi_ids = $row['oi_ids'];
                $oi_ids = explode(',', $oi_ids);
                $row['items'] = [];

                // 添加物流订单号
                $oi_ids = explode(',', $row['oi_ids']);
                foreach ($oi_ids as $oi_id) {
                    $row['items'][] = $item_map[$oi_id];
                }
            }
            $rows = array_column($rows,'items');
            $rows = call_user_func_array('array_merge',$rows);

            foreach ($rows as $row) {
                $data['all_price'] = $data['all_price'] + ($row['price']*$row['qty'] + $row['pack_price']);
                $data['all_qty'] = $data['all_qty'] + $row['qty'];
            }
        } catch (\Throwable $th) {
            //throw $th;
        }
        
        return $data;
    }
    protected function buildParams()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if (input('progress') === '0') {
            $where['progress'] = 0;
        }
        return $where;
    }
    protected function getItemsMap(&$rows)
    {
        $oi_ids = array_column($rows, 'oi_ids');
        $oi_ids = explode(',', implode(',', $oi_ids));
        $rows_map = Db::name('orders_item')->where('id', 'in', $oi_ids)
                                        ->column('id,order_id,order_sn,goods_id,color,spec,qty,price,remarks,progress,express,pack_price', 'id');

        //商品信息
        $goods_map = Db::name('goods')->where('id', 'in', array_column($rows_map, 'goods_id'))
                                    ->column('');
        $progress_desc = OrdersItem::$progress_desc;
        $size_sets = Goods::$size_sets;
        foreach($rows_map as &$row) {
            $goods_info          = $goods_map[$row['goods_id']];
            $row['goods_name']   = $goods_info['name'];
            $row['pic']          = config('upload_path') . $goods_info['picture'];
            $row['pic_tmb']      = $this->getThumb($row['pic']);
            $row['progress_txt'] = $progress_desc[$row['progress']];
            $row['can_ship']     = in_array($row['progress'], [1,2,3]);

            $size_set = $goods_map[$row['goods_id']]['size_set'];
            $row['size_set']     = explode(',', $size_sets[$size_set]);
        }
        //print_r($rows_map);
        return $rows_map;
    }
    public function getRelationList()
    {
        $oi_id = input('id');
        if (empty($oi_id)) {
            $this->error('缺少参数');
        }
        //报单记录
        $pur_rows = Purchase::with('stallInfo')->where('order_item_id', $oi_id)->select()->toArray();
  
        foreach ($pur_rows as &$row) {
            $row['add_time'] = date('Y-m-d, H:i', $row['add_time']);
            $row['acct_name'] = Db::name('account')->where('id', $row['acct_id'])->value('true_name');
        }

        //发货记录
        $exp_rows = ExpressItem::with('expressInfo')->where('order_item_id', $oi_id)->select()->toArray();
        foreach ($exp_rows as &$row) {
            $row['add_time'] = date('Y-m-d, H:i', $row['express_info']['add_time']);
            $row['acct_name'] = Db::name('account')->where('id', $row['express_info']['acct_id'])->value('true_name');
        }

        //取消记录
        $cancel_rows = Db::name('orders_item_cancel')->where('order_item_id', $oi_id)->select();
        $this->fomatTime($cancel_rows);
         // 获取团队 
         $account_id = Session::get('uid');
         // 团队（客服）隐藏，禁止报单功能,账户信息
         $user_info = Db::name('account')->where('id',$account_id)->find();
        //  订单列表-查看关联记录-报单-是否显示工厂价
        $rules = Rules::hasRules(7);
        $data = [
            'id'            => $oi_id,
            // 'pur_rows'      => ($user_info['role_id'] == 7 || $user_info['role_id'] == 2)?[]:$pur_rows,
            'pur_rows'      => !$rules?[]:$pur_rows,
            'exp_rows'      => $exp_rows,
            'user_info'     => $user_info
        ];
        if (empty($pur_rows) && empty($exp_rows)) {
            $data['id'] = 0;
        }
        $this->success('成功','',$data);
    }
    protected function fomatTime(&$rows)
    {
        foreach ($rows as &$row) {
            $row['add_time'] = date('Y-m-d, H:i', $row['add_time']);
        }
    }
    //到货订单
    public function stockList()
    {
        return view();
    }
    public function detail()
    {
        $order_id = input('id');

        $order = Orders::get($order_id);
        $order['items'] = OrdersItem::with('goodsInfo,expItems')
                                    ->where('order_id', $order_id)->select();
        //return $order['items'];
        $info = [
            'id'        => $order['id'],
            'order_no'  => $order['order_no'],
            'cust'      => $order['cust'],
            'phone'     => $order['phone'],
            'pay_type'  => Orders::$pay_types[$order['pay_type']],
            // 'addr'      => $order['area_path'] . $order['detail_addr'],//OOP
            'addr'      =>  $order['detail_addr'],
            'recv_day'  => $order['recv_day'],
        ];
        $size_sets = Goods::$size_sets;
        foreach ($order['items'] as $item) {
            $exp_qty = empty($item['exp_items']) ? 0 : array_sum(array_column($item['exp_items']->toArray(), 'qty'));
            $row = [
                'id'            => $item['id'],
                'order_sn'      => $item['order_sn'],
                'pic'           => config('upload_path') . $item['goods_info']['picture'],
                'pic_tmb'       => $this->getThumb(config('upload_path') . $item['goods_info']['picture']),
                'goods_name'    => $item['goods_info']['name'],
                'size_set'      => explode(',', $size_sets[$item['goods_info']['size_set']]),
                'color'         => $item['color'],
                'spec'          => $item['spec'],
                'price'         => $item['price'],
                'in_price'      => Db::name('purchase')->where('order_item_id',$item['id'])->value('price'),
                'qty'           => $item['qty'],
                'exp_qty'       => $exp_qty,
                'remarks'       => $item['remarks'],
                'progress'      => $item['progress'],
                'progress_desc' => OrdersItem::$progress_desc[$item['progress']],
            ];
            $items[] = $row;
        }
        $info['items'] = $items;

        $data['info'] = $info;
        $this->success('获取成功','',$data);
    }
    public function getItemInfo()
    {
        $order_item_id = input('id');
        //return $order_item_id;
        $pur_rows = Db::name('purchase')->where('order_item_id', $order_item_id)->select();
        $status_txt = [
            1   => '等待到货',
            2   => '已取消',
            3   => '已到货'
        ];

        foreach ($pur_rows as &$row) {
            $row['add_day'] = date('Y-m-d', $row['add_time']);
            $row['status_txt'] = $status_txt[$row['status']];
            $row['stall_name'] = Db::name('stall')->where('id', $row['stall_id'])->value('name');
        }

        $exp_rows = Db::name('express_item')->where('order_item_id', $order_item_id)->select();
        $exp_map = Db::name('express')->where('id', 'in', array_column($exp_rows, 'express_id'))->column('');
        foreach ($exp_rows as &$row) {
            $exp = $exp_map[$row['express_id']];
            $row['exp_name'] = $exp['name'];
            $row['add_day'] = date('Y-m-d', $exp['add_time']);
            $row['exp_no'] = $exp['express_no']; 
        }
        
        $info = [
            'pur_rows'  => $pur_rows,
            'exp_rows'  => $exp_rows
        ];

        $this->success('ok','',$info);
    }
    //订单添加页
    public function add()
    {	
    	//省份
    	$provinces = Db::name('area')->where('level','1')->select();
    	$this->assign([
    		'pay_types'	=> Orders::$pay_types,
    		'provinces'	=> $provinces,
    	]);
    	return view();
    }
    public function handle()
    {
        // 获取团队
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->find();
        // dump($account_member);die;
    	$data = input('post.');
    	//print_r($data);exit;
        $info = $data['info'];
        $validate = new Validate([
            ['cust','require','客户必须'],
            ['phone','require|length:11','电话必须|电话必须是11位手机号'],
            ['pay_type','require','请选择支付方式'],
            ['area_id','require','请选择地区'],
            ['detail_addr','require','地址必须'],
            ['recv_day','require','请选择接单日期'],
            ['exp_cost','require|number','运费必填|运费必须是数值'],
        ]);
        if (!$validate->check($info)) {
            return [
                'code'  => 0,
                'msg'   => $validate->getError()
            ];
        }
        if (empty($data['items'])) {
            $this->error('请选择商品');
        }
        $validate = new Validate([
            ['goods_id','require|number','error 01|error 02'],
            ['spec','require','请选择尺码'],
            ['color','require','颜色必需'],
            ['qty','require|number','数量必须|数量必须是数值'],
            ['price','require|number','单价必须|单价必须是数值'],
            ['express','require','请物流公司']
        ]);
        foreach ($data['items'] as $goods_key => $row) {
            if (!$validate->check($row)) {
                return [
                    'code'  => 0,
                    'msg'   => $validate->getError()
                ];
            }
            // 订单下的商品，添加商品分类
            $goods_id = $row['goods_id'];
            $type = Db::name('goods')->alias('g')->join('__GOODS_CATEGORIES__ gc','g.cate_id=gc.id')->where('g.id',$goods_id)->value('type');
            $data['items'][$goods_key]['goods_categories_type'] = $type;
            
            
        }
        $info['area_path'] = Db::name('area')->where('id',$info['area_id'])->value('name_path');
        $info['acct_id'] = Session::get('uid');
        // 订单添加团队
        if(!empty($account_member)){
            $info['organization_id'] = $account_member['organization_id'];
        }
        $order_model = new Orders();
        $res = $order_model->insert($info);
        if ($res['code'] ==0){
            $this->error($res['msg']);
        }

        $order_id = $res['order_id'];
        $order_items_model = new OrdersItem();
        $res2 = $order_items_model->insert($data['items'], $order_id);
        if ($res2['code'] ==0){
            $this->error($res2['msg'] + 'A');
        }

    	$this->success('添加成功','',$res['data']);
    }
    public function itemList()
    {
        return view();
    }
    public function getItemList()
    {
        $where = array_filter(input('post.'));

        // 添加日期搜索
        if(isset($where['date'])){
            $date1 = $where['date']['date1'];
            $date2 = $where['date']['date2'];
            unset($where['date']);
            if (!empty($date1) && !empty($date2)) {
                $date1 = strtotime($date1);
                $date2 = strtotime($date2) + 24*60*60;
            } else {
                $date1 = strtotime(date('Y-m-1'));
                $date2 = time();
            }
            $where['oi.add_time'] = ['between',[$date1, $date2]];
        }

        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if (input('progress') === '0') {
            $where['progress'] = 0;
        }
        if (input('progress') === '1-10') {
            $where['progress'] = ['in',['1','10']];
        }
        //print_r($where);
        $page = max(input('get.page',0),1);
        $page_size = 15;

        $orders_model = new Orders();
        // 获取团队 
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
        }
        $total = $orders_model->alias('o')->join('__ORDERS_ITEM__ oi','o.id=oi.order_id')
                                    ->join('__GOODS__ g','g.id=oi.goods_id')
                                    ->where($where)
                                    ->count();
        //return $orders_model->getLastSql();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }

        $items = $orders_model->alias('o')->join('__ORDERS_ITEM__ oi','o.id=oi.order_id')
                            ->join('__GOODS__ g','g.id=oi.goods_id')
                            ->where($where)
                            ->field('o.id as order_id,order_no,order_sn,cust,area_path,detail_addr,o.acct_id,o.add_time,oi.id,goods_id,spec,color,qty,price,remarks,progress,g.cate_id,brand_id,name,picture')
                            ->order('o.add_time desc')
                            ->page($page,$page_size)->select()->toArray();
        if (!empty($where['progress']) && $where['progress'] == 3) {
            $this->setStock($items);
        }
        //return $orders_model->getLastSql();
        //return $items;
        $acct_ids = array_unique( array_column($items, 'acct_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
        //return $acct_map;
        $progress_desc = OrdersItem::$progress_desc;
        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $item['picture'];
            $items[$key]['pic_tmb'] = $this->getThumb($items[$key]['pic']);
            $items[$key]['acct_name'] = $acct_map[$item['acct_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('H:i', $item['add_time']);
            $items[$key]['progress_desc'] = $progress_desc[$item['progress']];
        } 
        //分组               
        $orders = [];
        foreach ($items as $item) {
            $orders[$item['order_no']][] = $item;
        }
        krsort($orders);
        $rows = [];
        foreach ($orders as $order_no => $items) {
            $tmp = [
                'order_no' => $order_no,
                'items'    => $items
            ];
            $rows[] = $tmp;
        }
       
        $data['rows'] = $rows;
        // 团队（客服）隐藏，禁止报单功能,账户信息
        $data['user_info'] = Db::name('account')->where('id',$account_id)->find();
        $this->success('成功','',$data);
    }
    public function setStock(&$rows)
    {
        $model = Db::name('stock_in');
        foreach ($rows as &$row) {
            $where = [
                'order_item_id' => $row['id'],
                'status'        =>  1
            ];
            $row['stock_qty'] = $model->where($where)->sum('qty');
        }

    }
    
    //取消
    public function cancelItem()
    {
        $data = input('post.');
        $validate = new Validate([
            ['id','require','error1'],
            ['reason','require','请输入取消原因']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        
        $info = [
            'order_item_id' => $data['id'],
            'reason'        => $data['reason'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        // 获取订单团队
        $order_item_id = $data['id'];
        $order_item = Db::name('orders_item')->where('id',$order_item_id)->find();
        $order = Db::name('orders')->where('id',$order_item['order_id'])->find();
        $info['progress_status'] = $order_item['progress'];
        if(isset($order['organization_id'])){
            $info['organization_id'] = $order['organization_id'];
        }
        Db::name('orders_item_cancel')->insert($info);
        // 添加消息记录
        $log_data = [
            'account_id' => Session::get('uid'),
            'remark' => $data['reason'],
            'source_id' => $data['id'],
            'type' => 'cancel',
            'organization_id' => isset($info['organization_id'])?$info['organization_id']:''

        ];
        $this->project_log_model->add($log_data);
        //更新订单状态
        OrdersItem::update(['progress'=>0],['id'=>$data['id']]);
        
        $this->success('取消成功');
    }
    //退货
    public function handleReject()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['id','require','error1'],
            ['qty','require|number','数量必须|数量必须是数值'],
            ['reason','require','请输入退货原因']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $info = [
            'order_item_id' => $data['id'],
            'qty'           => $data['qty'],
            'reason'        => $data['reason'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        // 获取订单团队
        $order_item_id = $data['id'];
        $order_item = Db::name('orders_item')->where('id',$order_item_id)->find();
        $order = Db::name('orders')->where('id',$order_item['order_id'])->find();
        if(isset($order['organization_id'])){
            $info['organization_id'] = $order['organization_id'];
        }
        Db::name('orders_item_reject')->insert($info);
        $log_data = [
            'account_id' => Session::get('uid'),
            'remark' => $data['reason'],
            'source_id' => $data['id'],
            'type' => 'return',
            'organization_id' => isset($info['organization_id'])?$info['organization_id']:''

        ];
        $this->project_log_model->add($log_data);
        //更新订单状态
        OrdersItem::update(['progress'=>5],['id'=>$data['id']]);

        $this->success('操作成功');
    }
    //换货
    public function handleChange()
    {
        $data = input('post.');
        $validate = new Validate([
            ['id','require','error1'],
            ['qty','require|number','数量必须|数量必须是数值'],
            ['reason','require','请输入换货原因']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $info = [
            'order_item_id' => $data['id'],
            'qty'           => $data['qty'],
            'reason'        => $data['reason'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ];
        // 获取订单团队
        $order_item_id = $data['id'];
        $order_item = Db::name('orders_item')->where('id',$order_item_id)->find();
        $order = Db::name('orders')->where('id',$order_item['order_id'])->find();
        if(isset($order['organization_id'])){
            $info['organization_id'] = $order['organization_id'];
        }
        //获取账号
        Db::name('orders_item_change')->insert($info);
        //更新订单状态
        OrdersItem::update(['progress'=>6],['id'=>$data['id']]);

         $this->success('操作成功');
    }
    public function saveItem()
    {
        $data = input('post.');
        $validate = new Validate([
            ['id','require','error1'],
            ['spec','require','尺码必须'],
            ['qty','require|number','数量必须|数量必须是数值'],
            ['price','require|number','单价必须|单价必须是数值'],
            ['pack_price','require|number','单价必须|单价必须是数值'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //已发货不能改（团队需求，发货了要能修改价格）
        // $progress = Db::name('orders_item')->where('id',$data['id'])->value('progress');
        // if ($progress == 4){
        //     $this->error('已发货不能修改');
        // }
        $info = [
            'spec'      => $data['spec'],
            'price'     => $data['price'],
            'qty'       => $data['qty'],
            'remarks'   => $data['remarks'],
            'pack_price'     => $data['pack_price'],
        ];
        if (Db::name('orders_item')->where('id',$data['id'])->update($info)) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }
    public function changeList()
    {
        return view();
    }
    /**
     * 取消订单
     */
    public function refundList(){
        return view();
    }
    /**
     * 退货订单
     */
    public function returnList(){
        return view();
    }
    public function getChangeList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        
        // 获取团队 OOP
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['oc.organization_id'] = ['in',$organization_list];
        }
        
        //print_r($where);
        $page = max(input('get.page',0),1);
        $page_size = 15;

        $orders_model = new Orders();
        $total = Db::name('orders_item_change')->alias('oc')
                                    ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','oi.order_id=o.id')
                                    ->where($where)
                                    ->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }

        $items =  Db::name('orders_item_change')->alias('oc')
                            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                            ->join('__ORDERS__ o','oi.order_id=o.id')
                            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
                            ->where($where)
                            ->order('oc.add_time desc')
                            ->page($page,$page_size)->select();
        //账号信息
        $acct_ids = array_unique( array_column($items, 'saler_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
       
        //商品信息
        $goods_ids = array_unique( array_column($items, 'goods_id') );
        $goods_map = Db::name('goods')->where('id','in',$goods_ids)->column('');

        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $goods_map[$item['goods_id']]['picture'];
            $items[$key]['goods_name'] = $goods_map[$item['goods_id']]['name'];
            $items[$key]['saler'] = $acct_map[$item['saler_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('H:i', $item['add_time']);
        } 
        
        $data['rows'] = $items;
        $this->success('成功','',$data);
    }
    /**
     * 获取取消订单
     * @param type 售后状态，1售后中，2同意售后，售后完成
     */
    public function getCancelList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (isset($where['type'])) {
            $where['type'] = ['in',$where['type']];
        }
        // 添加时间查询
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            $where['oc.add_time'] = ['between',[$date1, $date2]];
            unset($where['date1']);
            unset($where['date2']);
        }
        // 添加退款时间查询
        if (!empty($where['date3']) && !empty($where['date4'])) {
            $date3 = strtotime($where['date3']);
            $date4 = strtotime($where['date4']) + 24*60*60;
            $where['oc.final_time'] = ['between',[$date3, $date4]];
            unset($where['date3']);
            unset($where['date4']);
        }
        // dump($where['date2']);die;
        // 获取团队 OOP
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['oc.organization_id'] = ['in',$organization_list];
        }
        if(!empty($where['organization_id'])){
            $where['oc.organization_id'] = $where['organization_id'];
            unset($where['organization_id']);
        }
        
        $page = max(input('get.page',0),1);
        $page_size = max(input('get.page_size',0),1);
        if(empty($page_size)){
            $page_size = 15;
        }
        $total = Db::name('orders_item_cancel')->alias('oc')
                                    ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','oi.order_id=o.id')
                                    ->where($where)
                                    ->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }
        // 显示报单价权限
        $pur_price_rules = Rules::hasRules('4');
        if($pur_price_rules){
            $items =  $this->cancel_model->alias('oc')
            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
            ->join('__ORDERS__ o','oi.order_id=o.id')
            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
            ->where($where)
            ->order('oc.add_time desc')
            ->page($page,$page_size)->select();
            $items = collection($items)->toArray();
        }else{
            $items =  Db::name('orders_item_cancel')->alias('oc')
            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
            ->join('__ORDERS__ o','oi.order_id=o.id')
            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
            ->where($where)
            ->order('oc.add_time desc')
            ->page($page,$page_size)->select();
        }
        // $items =  Db::name('orders_item_cancel')->alias('oc')
        //                     ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
        //                     ->join('__ORDERS__ o','oi.order_id=o.id')
        //                     ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
        //                     ->where($where)
        //                     ->order('oc.add_time desc')
        //                     ->page($page,$page_size)->select();
        
        //账号信息
        
        $acct_ids = array_unique( array_column($items, 'saler_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
       
        //商品信息
        $goods_ids = array_unique( array_column($items, 'goods_id') );
        $goods_map = Db::name('goods')->where('id','in',$goods_ids)->column('');

        foreach ($items as $key => $item) {
            $items[$key]['pic'] = isset($goods_map[$item['goods_id']])?config('upload_path') . $goods_map[$item['goods_id']]['picture']:'未找到商品';
            $items[$key]['goods_name'] = isset($goods_map[$item['goods_id']])?$goods_map[$item['goods_id']]['name']:'未找到商品';
            $items[$key]['saler'] = $acct_map[$item['saler_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('H:i', $item['add_time']);
            $items[$key]['final_time'] = $item['final_time']?date('Y-m-d H:i', $item['final_time']):null;
        } 
        
        $data['rows'] = $items;
        $data['is_pur_price'] = $pur_price_rules;
        $this->success('成功','',$data);
    }
     /**
     * 导出取消订单
     * @param type 售后状态，1售后中，2同意售后，售后完成
     */
    public function getCancelListExcel()
    {
        $where = array_filter(input('get.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (isset($where['type'])) {
            $where['type'] = ['in',explode(',',$where['type'])];
        }
        // 添加时间查询
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            $where['oc.add_time'] = ['between',[$date1, $date2]];
            unset($where['date1']);
            unset($where['date2']);
        }
         // 添加退款时间查询
         if (!empty($where['date3']) && !empty($where['date4'])) {
            $date3 = strtotime($where['date3']);
            $date4 = strtotime($where['date4']) + 24*60*60;
            $where['oc.final_time'] = ['between',[$date3, $date4]];
            unset($where['date3']);
            unset($where['date4']);
        }
        // 防止查询报错
        unset($where['page']);
        unset($where['page_size']);
        // 获取团队 OOP
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['oc.organization_id'] = ['in',$organization_list];
        }
        if(!empty($where['organization_id'])){
            $where['oc.organization_id'] = $where['organization_id'];
            unset($where['organization_id']);
        }
        
        $page = max(input('get.page',0),1);
        $page_size = max(input('get.page_size',0),1);
        if(empty($page_size)){
            $page_size = 15;
        }
        $total = Db::name('orders_item_cancel')->alias('oc')
                                    ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','oi.order_id=o.id')
                                    ->where($where)
                                    ->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('没有数据','',$data);
        }
        // 显示报单价权限
        $pur_price_rules = Rules::hasRules('4');
        if($pur_price_rules){
            $items =  $this->cancel_model->alias('oc')
            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
            ->join('__ORDERS__ o','oi.order_id=o.id')
            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
            ->where($where)
            ->order('oc.add_time desc')
            ->page($page,$page_size)->select();
            $items = collection($items)->toArray();
        }else{
            $items =  Db::name('orders_item_cancel')->alias('oc')
            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
            ->join('__ORDERS__ o','oi.order_id=o.id')
            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
            ->where($where)
            ->order('oc.add_time desc')
            ->page($page,$page_size)->select();
        }
        // $items =  Db::name('orders_item_cancel')->alias('oc')
        //                     ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
        //                     ->join('__ORDERS__ o','oi.order_id=o.id')
        //                     ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
        //                     ->where($where)
        //                     ->order('oc.add_time desc')
        //                     ->page($page,$page_size)->select();
        //账号信息
        $acct_ids = array_unique( array_column($items, 'saler_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
       
        //商品信息
        $goods_ids = array_unique( array_column($items, 'goods_id') );
        $goods_map = Db::name('goods')->where('id','in',$goods_ids)->column('');

        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $goods_map[$item['goods_id']]['picture'];
            $items[$key]['goods_name'] = $goods_map[$item['goods_id']]['name'];
            $items[$key]['saler'] = $acct_map[$item['saler_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('Y-m-d H:i', $item['add_time']);
            $items[$key]['final_time'] = $item['final_time']?date('Y-m-d H:i', $item['final_time']):null;
        } 
        
        $data['rows'] = $items;
        $head_name_list = LibraryOrders::orderCancelAttr($pur_price_rules);
        $this->excel($data['rows'],null,$head_name_list);
    }
    /**
     * 同意售后订单（取消订单）
     */
    public function agreeCancel()
    {
        $id = $this->request->param('id');
        $res = Db::name('orders_item_cancel')->where('id',$id)->update(['type'=>'2']);
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 完成售后订单（取消订单）
     */
    public function finalCancel()
    {
        $id = $this->request->param('id');
        $res = Db::name('orders_item_cancel')->where('id',$id)->update(['type'=>'3','final_time'=>time()]);
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 修改属性（取消订单）
     * @param type 退款类型
     */
    public function setCancelAtrr()
    {
        $id = $this->request->param('id');
        $refund_total = $this->request->param('refund_total');
        $cancel_type = $this->request->param('cancel_type');
        $type = $this->request->param('type');
        if($type == 'cancel_type'){//设置取消订单类型
            $res = Db::name('orders_item_cancel')->where('id',$id)->update(['cancel_type'=>$cancel_type]);
        }else{//设置退款金额
            $res = Db::name('orders_item_cancel')->where('id',$id)->update(['refund_total'=>$refund_total]);
        }
        
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
     /**
     * 获取退货订单
     * @param type 售后状态，1售后中，2同意售后，售后完成
     * @param organization_id 团队id
     */
    public function getReturnList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (isset($where['type'])) {
            $where['type'] = ['in',$where['type']];
        }
        // 添加时间查询
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            $where['oc.add_time'] = ['between',[$date1, $date2]];
            unset($where['date1']);
            unset($where['date2']);
        }
         // 添加退款时间查询
         if (!empty($where['date3']) && !empty($where['date4'])) {
            $date3 = strtotime($where['date3']);
            $date4 = strtotime($where['date4']) + 24*60*60;
            $where['oc.final_time'] = ['between',[$date3, $date4]];
            unset($where['date3']);
            unset($where['date4']);
        }
        // 获取团队 OOP
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['oc.organization_id'] = ['in',$organization_list];
        }
        // 团队查询条件
        if(!empty($where['organization_id'])){
            $where['oc.organization_id'] = $where['organization_id'];
            unset($where['organization_id']);
        }
        
        $page = max(input('get.page',0),1);
        $page_size = max(input('get.page_size',0),1);
        if(empty($page_size)){
            $page_size = 15;
        }
        $total = Db::name('orders_item_reject')->alias('oc')
                                    ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','oi.order_id=o.id')
                                    ->where($where)
                                    ->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }
         // 显示报单价权限
         $pur_price_rules = Rules::hasRules('4');
         if($pur_price_rules){
             $items =  $this->reject_model->alias('oc')
             ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
            ->join('__ORDERS__ o','oi.order_id=o.id')
            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
            ->where($where)
            ->order('oc.add_time desc')
            ->page($page,$page_size)->select();
             $items = collection($items)->toArray();
         }else{
             $items =  Db::name('orders_item_reject')->alias('oc')
                            ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                            ->join('__ORDERS__ o','oi.order_id=o.id')
                            ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
                            ->where($where)
                            ->order('oc.add_time desc')
                            ->page($page,$page_size)->select();
         }
        // $items =  Db::name('orders_item_reject')->alias('oc')
        //                     ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
        //                     ->join('__ORDERS__ o','oi.order_id=o.id')
        //                     ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
        //                     ->where($where)
        //                     ->order('oc.add_time desc')
        //                     ->page($page,$page_size)->select();
        //账号信息
        $acct_ids = array_unique( array_column($items, 'saler_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
       
        //商品信息
        $goods_ids = array_unique( array_column($items, 'goods_id') );
        $goods_map = Db::name('goods')->where('id','in',$goods_ids)->column('');

        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $goods_map[$item['goods_id']]['picture'];
            $items[$key]['goods_name'] = $goods_map[$item['goods_id']]['name'];
            $items[$key]['saler'] = $acct_map[$item['saler_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('H:i', $item['add_time']);
            $items[$key]['final_time'] = $item['final_time']?date('Y-m-d H:i', $item['final_time']):null;
        } 
        
        $data['rows'] = $items;
        $data['is_pur_price'] = $pur_price_rules;
        $this->success('成功','',$data);
    }
    /**
     * 导出退货订单
     * @param type 售后状态，1售后中，2同意售后，售后完成
     * @param organization_id 团队id
     */
    public function getReturnListExcel()
    {
        $where = array_filter(input('get.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (isset($where['type'])) {
            $where['type'] = ['in',explode(',',$where['type'])];
        }
        // 添加时间查询
        if (!empty($where['date1']) && !empty($where['date2'])) {
            $date1 = strtotime($where['date1']);
            $date2 = strtotime($where['date2']) + 24*60*60;
            $where['oc.add_time'] = ['between',[$date1, $date2]];
            unset($where['date1']);
            unset($where['date2']);
        }
         // 添加退款时间查询
         if (!empty($where['date3']) && !empty($where['date4'])) {
            $date3 = strtotime($where['date3']);
            $date4 = strtotime($where['date4']) + 24*60*60;
            $where['oc.final_time'] = ['between',[$date3, $date4]];
            unset($where['date3']);
            unset($where['date4']);
        }
        // 防止查询报错
        unset($where['page']);
        unset($where['page_size']);
        // 获取团队 OOP
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['oc.organization_id'] = ['in',$organization_list];
        }
        // 团队查询条件
        if(!empty($where['organization_id'])&&$where['organization_id'] != 'null'){
            $where['oc.organization_id'] = $where['organization_id'];
            unset($where['organization_id']);
        }
        // dump($where);die;
        $page = max(input('get.page',0),1);
        $page_size = max(input('get.page_size',0),1);
        if(empty($page_size)){
            $page_size = 15;
        }
        $total = Db::name('orders_item_reject')->alias('oc')
                                    ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','oi.order_id=o.id')
                                    ->where($where)
                                    ->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('没有数据','',$data);
        }
         // 显示报单价权限
         $pur_price_rules = Rules::hasRules('4');
         if($pur_price_rules){
             $items =  $this->reject_model->alias('oc')
             ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
             ->join('__ORDERS__ o','oi.order_id=o.id')
             ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
             ->where($where)
             ->order('oc.add_time desc')
             ->page($page,$page_size)->select();
             
         }else{
             $items =  $this->reject_model->alias('oc')
             ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
             ->join('__ORDERS__ o','oi.order_id=o.id')
             ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
             ->where($where)
             ->order('oc.add_time desc')
             ->page($page,$page_size)->select();
         }
         $items = collection($items)->toArray();
        // $items =  Db::name('orders_item_reject')->alias('oc')
        //                     ->join('__ORDERS_ITEM__ oi','oc.order_item_id=oi.id')
        //                     ->join('__ORDERS__ o','oi.order_id=o.id')
        //                     ->field('oc.*,goods_id,spec,color,oi.qty as order_qty,price,order_no,cust,o.acct_id as saler_id')
        //                     ->where($where)
        //                     ->order('oc.add_time desc')
        //                     ->page($page,$page_size)->select();
        //账号信息
        $acct_ids = array_unique( array_column($items, 'saler_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
       
        //商品信息
        $goods_ids = array_unique( array_column($items, 'goods_id') );
        $goods_map = Db::name('goods')->where('id','in',$goods_ids)->column('');

        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $goods_map[$item['goods_id']]['picture'];
            $items[$key]['goods_name'] = $goods_map[$item['goods_id']]['name'];
            $items[$key]['saler'] = $acct_map[$item['saler_id']]['true_name'];
            // $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('Y-m-d H:i', $item['add_time']);
            $items[$key]['final_time'] = $item['final_time']?date('Y-m-d H:i', $item['final_time']):null;
        } 

        $data['rows'] = $items;
        $head_name_list = LibraryOrders::orderReturnAttr($pur_price_rules);
        $this->excel($data['rows'],null,$head_name_list);
    }
    /**
     * 同意售后订单（退货订单）
     */
    public function agreeReturn()
    {
        $id = $this->request->param('id');
        $res = Db::name('orders_item_reject')->where('id',$id)->update(['type'=>'2']);
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 同意售后订单（退货订单）
     */
    public function finalReturn()
    {
        $id = $this->request->param('id');
        $res = Db::name('orders_item_reject')->where('id',$id)->update(['type'=>'3','final_time'=>time()]);
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 同意售后订单（退货订单）
     */
    public function delReturn()
    {
        $id = $this->request->param('id');
        $order_item_id = Db::name('orders_item_reject')->where('id',$id)->value('order_item_id');
        $res = Db::name('orders_item_reject')->where('id',$id)->delete();
        if(!empty($res)){
            Db::name('orders_item')->where('id',$order_item_id)->update(['progress' => 4]);
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 同意售后订单（取消订单）
     */
    public function delCancel()
    {
        $id = $this->request->param('id');
        $orders_item_cancel = Db::name('orders_item_cancel')->where('id',$id)->find();
        if(!empty($orders_item_cancel['progress_status'])){
            Db::name('orders_item')->where('id',$orders_item_cancel['order_item_id'])->update(['progress' => $orders_item_cancel['progress_status']]);
            $res = Db::name('orders_item_cancel')->where('id',$id)->delete();
            $this->success('操作成功');
        }else{
            $this->error('操作失败，旧数据无法取消');
        }
    }
    /**
     * 修改属性（取消订单）
     */
    public function setReturnAtrr()
    {
        $id = $this->request->param('id');
        $refund_total = $this->request->param('refund_total');
        $res = Db::name('orders_item_reject')->where('id',$id)->update(['refund_total'=>$refund_total]);
        if(!empty($res)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 现金报表
     */
    public function financeList()
    {
        return view();
    }
    /**
     * 统计销售业绩
     */
    public function getFinanceList($page=1,$page_size=50)
    {
        $params = input('post.')['search'];

        if (!empty($params['date1']) && !empty($params['date2'])) {
            $date1 = strtotime($params['date1']);
            $date2 = strtotime($params['date2']) + 24*60*60;
        } else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where['oi.add_time'] = ['between',[$date1, $date2]];
        if (!empty($params['saler'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$params['saler'])->value('id');
        }
        if (!empty($params['cust'])) {
            $where['o.cust'] = $params['cust'];
        }
        
        // 只能查询所在团队数据
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['o.organization_id'] = ['in',$organization_list];
        }
        if(!empty($params['organization_id'])){
            if($params['organization_id'] == 'no_organization'&&Rules::hasRules('6')){//查询无团队数据
                $where['o.organization_id'] = null;
            }else{//查询团队数据
                $where['o.organization_id'] = $params['organization_id'];
            }
            
        }
        if(!empty($params['goods_categories_type'])){
            $where['goods_categories_type'] = $params['goods_categories_type'];
        }

        $page = empty($_POST['page']) ? 10 : $_POST['page'];

        $oi_model = new OrdersItem();

        // 计算业绩
        $total_list = [];
        // 售价金额总和
        $sell_total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where($where)->field('sum(price*qty+pack_price) as totals')->find();
        $total_list['sell_total'] = $sell_total['totals'];
        // 退款售价金额总和
        $refund_total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where(['progress'=>['in',[0,5]]])->where($where)->field('sum(price*qty+pack_price) as totals')->find();
        $total_list['refund_total'] = $refund_total['totals'];

        // 报价金额总和
        $purchase_total = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty) as totals')
        ->find();
        $total_list['purchase_total'] = $purchase_total['totals'];
        // 退款报价金额总和
        $refund_purchase_total = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2],'progress'=>['in',[0,5]]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty) as totals')
        ->find();
        $total_list['refund_purchase_total'] = $refund_purchase_total['totals'];
        // 运费
        $purchase_total2 = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty+factory_price) as totals')
        ->find();
        $total_list['purchase_total2'] = $purchase_total2['totals'];
        // 退款报价金额总和
        $refund_purchase_total2 = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2],'progress'=>['in',[0,5]]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty+factory_price) as totals')
        ->find();
        $total_list['refund_purchase_total2'] = $refund_purchase_total2['totals'];
        // 计算利润
        // 售价利润
        $total_list['sell_profit'] = bcsub($sell_total['totals'],$refund_total['totals'],2);
        // 报价利润
        $total_list['purchase_profit'] = bcsub($purchase_total['totals'],$refund_purchase_total['totals'],2);
        $total_list['purchase_profit2'] = $purchase_total2['totals'] - $refund_purchase_total2['totals'];

        $total_list = [
            ['name'=>'售价+运费/包装','all'=>$total_list['sell_total'],'refund'=>$total_list['refund_total'],'total'=>$total_list['sell_profit']],
            ['name'=>'报价','all'=>$total_list['purchase_total'],'refund'=>$total_list['refund_purchase_total'],'total'=>$total_list['purchase_profit']],
            ['name'=>'报价+运费','all'=>$total_list['purchase_total2'],'refund'=>$total_list['refund_purchase_total2'],'total'=>$total_list['purchase_profit2']]
        ];

        $total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where($where)->count();
        $rows = $oi_model->alias('oi')
                        ->join('__ORDERS__ o','order_id=o.id')
                        ->where($where)
                        ->page($page,$page_size)
                        ->field('oi.*,order_no,recv_day,cust,phone,area_path,detail_addr,pay_type,acct_id')
                        ->order('oi.id')
                        ->select()->toArray();
        //商品信息
        $goods_map = $oi_model->getRelationInfo($rows, 'goods', 'goods_id');
        //账号信息
        $acct_map = $oi_model->getRelationInfo($rows, 'account', 'acct_id');
        //报单信息
        $oi_ids = array_column($rows, 'id');
        $where_p = [
            'order_item_id' => ['in', $oi_ids],
            'status'        => ['neq',2]
        ];
        $purchase_rows = Db::name('purchase')->where($where_p)->select();
        //return $purchase_rows;
        $pur_rows_g = [];
        foreach ($purchase_rows as $row) {
            $pur_rows_g[$row['order_item_id']][] = $row;
        }
        //print_r($pur_rows_g);exit;
        //档口信息
        $stall_map = $oi_model->getRelationInfo($purchase_rows, 'stall', 'stall_id');
        //物流信息
        // $exp_items = Db::name('express_item')->where('order_item_id','in',$oi_ids)->select();
        // $exp_map = $oi_model->getRelationInfo($exp_items, 'express', 'express_id');
        //return $stall_map;
        $progress_desc = OrdersItem::$progress_desc;
        $pay_types = Orders::$pay_types;
        foreach ($rows as &$row) {
            $row['acct_name'] = $acct_map[$row['acct_id']]['true_name'];
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
            $row['pay_type'] = $pay_types[$row['pay_type']];
            
            try{
                $goods = $goods_map[$row['goods_id']];
                $row['goods_info'] = [
                    'id'      => $goods['id'],
                    'name'    => $goods['name'],
                ];
            }catch(Exception $e){
                $row['goods_info'] = [
                    'id'      => uniqid(),
                    'name'    => '商品未找到',
                ];
            }
            


            $row['purchase_times'] = empty($pur_rows_g[$row['id']]) ? 0 : count($pur_rows_g[$row['id']]);
            $row['purchase_price'] = 0;
            $row['factory_price'] = 0;
            $row['stall_name'] = '';
            $row['purchase_name'] = '';
            if ($row['purchase_times'] > 0){
                $row['purchase_price'] = $pur_rows_g[$row['id']][0]['price'];
                $row['factory_price'] = $pur_rows_g[$row['id']][0]['factory_price'];
                $stall = $stall_map[$pur_rows_g[$row['id']][0]['stall_id']];
                $row['stall_name'] = $stall['name'];
                $p_uid = $pur_rows_g[$row['id']][0]['acct_id'];
                $row['purchase_name'] = Db::name('account')->where('id',$p_uid)->value('true_name');
            }
            //物流
            // $rows[$key]['exp_name'] = '';
            // $rows[$key]['exp_no'] = '';
            // if (count($row['exp_items'])){
            //     $exp = $exp_map[$row['exp_items'][0]['express_id']];
            //     $rows[$key]['exp_name'] = $exp['name'];
            //     $rows[$key]['exp_no'] = $exp['express_no'];
            // }
            $row['exp_name'] = '';
            $row['exp_no'] = '';
            $row['exp_time'] = '';
            $exp_items = Db::name('express_item')->alias('ei')
            ->join('__EXPRESS__ e','ei.express_id=e.id')
            ->where('order_item_id',$row['id'])
            ->field('e.*')
            ->find();
            if(!empty($exp_items)){
                $row['exp_no'] = $exp_items['express_no'];
                $row['exp_name'] = $exp_items['name'];
                $row['exp_time'] = date('Y-m-d H:i:s',$exp_items['add_time']);
            }

            $row['progress_txt'] = $progress_desc[$row['progress']];
        }
        //return $order_items;
        $data = array(
            'rows'          => $rows,
            'total_page'    => ceil($total/$page_size),
            'cur_page'      => $page,
            'total_list'         => $total_list,
            'organization'  =>$account_member
        );
        $this->success('成功','',$data);
    }
    public function oiList()
    {
        return view();
    }
    public function getOiList($page=1,$page_size=50)
    {
        $params = input('post.')['search'];

        if (!empty($params['date1']) && !empty($params['date2'])) {
            $date1 = strtotime($params['date1']);
            $date2 = strtotime($params['date2']) + 24*60*60;
        } else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where['oi.add_time'] = ['between',[$date1, $date2]];
        if (!empty($params['saler'])) {
            $where['acct_id'] = Db::name('account')->where('true_name',$params['saler'])->value('id');
        }
        if (!empty($params['cust'])) {
            $where['cust'] = $params['cust'];
        }
        
        
        // 只能查询所在团队数据
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
        }
        if(!empty($params['organization_id'])){
            if($params['organization_id'] == 'no_organization'&&Rules::hasRules('6')){//查询无团队数据
                $where['o.organization_id'] = null;
            }else{//查询团队数据
                $where['o.organization_id'] = $params['organization_id'];
            }
            // $where['organization_id'] = $params['organization_id'];
        }
        if(!empty($params['goods_categories_type'])){
            $where['goods_categories_type'] = $params['goods_categories_type'];
        }
        //$where = [];
        $page = empty($_POST['page']) ? 10 : $_POST['page'];

        $oi_model = new OrdersItem();
        $total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where($where)->count();
        $rows = $oi_model->alias('oi')
                        ->join('__ORDERS__ o','order_id=o.id')
                        ->where($where)
                        ->page($page,$page_size)
                        ->field('oi.*,order_no,recv_day,cust,phone,area_path,pay_type,acct_id')
                        ->order('oi.id')
                        ->select()->toArray();
        //商品信息
        $goods_map = $oi_model->getRelationInfo($rows, 'goods', 'goods_id');
        //账号信息
        $acct_map = $oi_model->getRelationInfo($rows, 'account', 'acct_id');
        //报单信息
        $oi_ids = array_column($rows, 'id');
        $where_p = [
            'order_item_id' => ['in', $oi_ids],
            'status'        => ['neq',2]
        ];
        $purchase_rows = Db::name('purchase')->where($where_p)->select();
        //return $purchase_rows;
        $pur_rows_g = [];
        foreach ($purchase_rows as $row) {
            $pur_rows_g[$row['order_item_id']][] = $row;
        }
        //print_r($pur_rows_g);exit;
        //档口信息
        $stall_map = $oi_model->getRelationInfo($purchase_rows, 'stall', 'stall_id');
        //物流信息
        $exp_items = Db::name('express_item')->where('order_item_id','in',$oi_ids)->select();
        $exp_map = $oi_model->getRelationInfo($exp_items, 'express', 'express_id');
        //return $stall_map;
        $progress_desc = OrdersItem::$progress_desc;
        $pay_types = Orders::$pay_types;
        foreach ($rows as &$row) {
            $row['acct_name'] = $acct_map[$row['acct_id']]['true_name'];
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
            $row['pay_type'] = $pay_types[$row['pay_type']];
            
            $goods = $goods_map[$row['goods_id']];
            $row['goods_info'] = [
                'id'      => $goods['id'],
                'name'    => $goods['name'],
            ];


            $row['purchase_times'] = empty($pur_rows_g[$row['id']]) ? 0 : count($pur_rows_g[$row['id']]);
            $row['purchase_price'] = 0;
            $row['stall_name'] = '';
            if ($row['purchase_times'] > 0){
                $row['purchase_price'] = $pur_rows_g[$row['id']][0]['price'];
                $stall = $stall_map[$pur_rows_g[$row['id']][0]['stall_id']];
                $row['stall_name'] = $stall['name'];
            }
            //物流
            // $rows[$key]['exp_name'] = '';
            // $rows[$key]['exp_no'] = '';
            // if (count($row['exp_items'])){
            //     $exp = $exp_map[$row['exp_items'][0]['express_id']];
            //     $rows[$key]['exp_name'] = $exp['name'];
            //     $rows[$key]['exp_no'] = $exp['express_no'];
            // }
            $row['progress_txt'] = $progress_desc[$row['progress']];
        }
        //return $order_items;
        $data = array(
            'rows'          => $rows,
            'total_page'    => ceil($total/$page_size),
            'cur_page'      => $page,
        );
        $this->success('成功','',$data);
    }
    // 导出订单
    public function exportExcle($page=1,$page_size=50)
    {
        // $params = input('get.')['search'];
        $params = $this->request->param();
        // dump($params);die;
        if (isset($params['date1'])&&!empty($params['date1']) && !empty($params['date2'])) {
            $date1 = strtotime($params['date1']);
            $date2 = strtotime($params['date2']) + 24*60*60;
        } else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where['oi.add_time'] = ['between',[$date1, $date2]];
        if (!empty($params['saler'])) {
            $where['acct_id'] = Db::name('account')->where('true_name',$params['saler'])->value('id');
        }
        if (!empty($params['cust'])) {
            $where['cust'] = $params['cust'];
        }
       
        
        // 只能查询所在团队数据
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
            $head_name_list = LibraryOrders::orderDetailAttr();
        }else{
            $head_name_list = LibraryOrders::orderDetailAttrFactory();
        }
        if(!empty($params['organization_id'])){
            if($params['organization_id'] == 'no_organization'&&Rules::hasRules('6')){//查询无团队数据
                $where['o.organization_id'] = null;
            }else{//查询团队数据
                $where['o.organization_id'] = $params['organization_id'];
            }
            // $where['organization_id'] = $params['organization_id'];
        }
        if(!empty($params['goods_categories_type'])){
            $where['goods_categories_type'] = $params['goods_categories_type'];
        }
        //$where = [];
        // $page = empty($_POST['page']) ? 10 : $_POST['page'];
        $page = $this->request->param('page');
        $page_size = $this->request->param('page_size')?:$page_size;
        // dump($where);die;
        $oi_model = new OrdersItem();
        // $total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where($where)->count();
        $rows = $oi_model->alias('oi')
                        ->join('__ORDERS__ o','order_id=o.id')
                        ->where($where)
                        // ->page($page,$page_size)
                        ->field('oi.*,order_no,recv_day,cust,phone,area_path,detail_addr,pay_type,acct_id')
                        ->order('oi.id')
                        ->select()->toArray();
        //商品信息
        $goods_map = $oi_model->getRelationInfo($rows, 'goods', 'goods_id');
        //账号信息
        $acct_map = $oi_model->getRelationInfo($rows, 'account', 'acct_id');
        //报单信息
        $oi_ids = array_column($rows, 'id');
        $where_p = [
            'order_item_id' => ['in', $oi_ids],
            'status'        => ['neq',2]
        ];
        $purchase_rows = Db::name('purchase')->where($where_p)->select();
        $pur_rows_g = [];
        foreach ($purchase_rows as $row) {
            $pur_rows_g[$row['order_item_id']][] = $row;
        }
        //档口信息
        $stall_map = $oi_model->getRelationInfo($purchase_rows, 'stall', 'stall_id');
        //物流信息
        // $exp_items = Db::name('express_item')->where('order_item_id','in',$oi_ids)->select();
        // $exp_map = $oi_model->getRelationInfo($exp_items, 'express', 'express_id');
        $progress_desc = OrdersItem::$progress_desc;
        $pay_types = Orders::$pay_types;
        foreach ($rows as &$row) {
            $row['acct_name'] = $acct_map[$row['acct_id']]['true_name'];
            $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);
            $row['pay_type'] = $pay_types[$row['pay_type']];
            
            // $goods = $goods_map[$row['goods_id']];
            // $row['goods_info'] = $goods['name'];
            try{
                $goods = $goods_map[$row['goods_id']];
                $row['goods_info'] = $goods['name'];
            }catch(Exception $e){
                $row['goods_info'] = '商品未找到';
            }

            $row['purchase_times'] = empty($pur_rows_g[$row['id']]) ? 0 : count($pur_rows_g[$row['id']]);
            $row['purchase_price'] = 0;
            $row['factory_price'] = 0;
            $row['stall_name'] = '';
            $row['purchase_name'] = '';
            if ($row['purchase_times'] > 0){
                $row['purchase_price'] = $pur_rows_g[$row['id']][0]['price'];
                if(empty($account_member)){
                    $row['factory_price'] = $pur_rows_g[$row['id']][0]['factory_price'];
                }
                $stall = $stall_map[$pur_rows_g[$row['id']][0]['stall_id']];
                $row['stall_name'] = $stall['name'];
                $p_uid = $pur_rows_g[$row['id']][0]['acct_id'];
                $row['purchase_name'] = Db::name('account')->where('id',$p_uid)->value('true_name');
            }
            // $row['exp_name'] = '';
            $row['exp_no'] = '';
            $exp_items['exp_time'] = '';
            $exp_items = Db::name('express_item')->alias('ei')
            ->join('__EXPRESS__ e','ei.express_id=e.id')
            ->where('order_item_id',$row['id'])
            ->field('e.*')
            ->find();
            if(!empty($exp_items)){
                $row['exp_no'] = $exp_items['name'].':'.$exp_items['express_no'];
                $row['exp_time'] = date('Y-m-d H:i:s',$exp_items['add_time']);
                // $row['exp_name'] = $exp_items['name'];
            }
            $row['progress_txt'] = $progress_desc[$row['progress']];
        }
        // $head_name_list = LibraryOrders::orderDetailAttr();
        $this->excel($rows,null,$head_name_list);
    }
    public function test()
    {
        //echo __CLASS__;
        // print_r(get_class_methods(__CLASS__));
        // foreach ($this as $key => $value) {
        //     echo $key . '->' . $value . '<br>';
        // }
    }
    public function setStatus()
    {
        $info['progress'] = input('progress');

        if (Db::name('orders_item')->where('id',input('id'))->update($info)) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }
    /**
     * 编辑订单地址
     * @param id 订单id
     * @param area_path 区域
     * @param detail_addr 详细地址
     */
    public function editAddr(){
        $params = $this->request->param();
        extract($params);
        // 发货不能修改地址
        $item = OrdersItem::where(['order_id'=>$id,'progress'=>4])->find();
        if(!empty($item)){
            $this->error('订单已经发货');
        }
        $res = Orders::where('id',$id)->update(['area_path'=>$area_path,'detail_addr'=>$detail_addr,'phone'=>$phone,'cust'=>$cust]);
        if(!empty($res)){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 计算提成
     */
    public function commission(){
        return view();
    }
    public function commissionList()
    {
        $where = [];
        $params = $this->request->param();

        
        if (!empty($params['date2'])) {
            $date = date('Y-m-d',strtotime($params['date2']));
            $date1 = strtotime($date);
            $date2 = date('Y-m-d', strtotime (date ('Y-m-01', strtotime ($date)) . "+1 month -1 day"));
            $date2 = strtotime($date2);
        } else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where_order['o.add_time'] = ['between',[$date1, $date2]];

        $page = max(input('get.page',0),1);

        $status = $this->request->param('status');
        $page_size = $this->request->param('page_size');
        if(empty($page_size )){
            $page_size = 20;
        }
        
        if(!empty($status)){
            // 过滤掉没有启用的账号
            $where['status'] = 1;
        }
        $where['role_id'] = ['in',[1,2,3,4,5,6,7,0]];
        $account = new \app\common\model\Account();
        $total = $account->where($where)->count();
        $rows = $account->with('accountMember,roles')->where($where)->field('password',true)->page($page,$page_size)->select()->toArray();
        $status_txt = Account::$status_txt;
        $role_txt = Account::$role_txt;
        $oi_model = new OrdersItem();
        // 销售价
        $acct_total = $oi_model->alias('oi')
            ->join('__ORDERS__ o','order_id=o.id')
            ->join('__PURCHASE__ p','p.order_item_id=oi.id')
            ->where(['oi.progress'=>['in',$params['progress'] ?: [4,6]]])
            ->where($where_order)
            ->group("o.acct_id")
            // ->column('sum(p.price*qty) as totals','o.acct_id');
            ->column('sum(oi.price*qty) as totals','o.acct_id');
        //成本价
        $per_total = $oi_model->alias('oi')
            ->join('__ORDERS__ o','order_id=o.id')
            ->join('__PURCHASE__ p','p.order_item_id=oi.id')
            ->where(['oi.progress'=>['in',$params['progress'] ?: [4,6]]])
            ->where($where_order)
            ->group("o.acct_id")
            ->column('sum(p.price*qty) as totals','o.acct_id');
            // ->column('sum(oi.price*qty) as totals','o.acct_id');

        
        


        foreach ($rows as $key => $row) {
            // 获取独立的业绩配置
            $commission = Db::name('commission')->where(['acct_id' => $row['id'], 'type_money' => $params['type_money']])->field('num,num_lower,num_d,num_big' )->find();
            if(empty($commission)){
                // 获取公用的业绩配置
                $commission = Db::name('config_value')->where('config_key','commissionSetting')->value('value');
                $commission = json_decode($commission, true);
            }
            $rows[$key]['commission'] = $commission;
            // 月目标业绩
            $num = $commission['num'];
            // 小于月目标业绩2%
            $num_lower = $commission['num_lower']/100;
            //等于月目标业绩3%
            $num_d = $commission['num_d']/100;
            //超出月目标业绩5%
            $num_big = $commission['num_big']/100;
            
            
            // 售价业绩 和 提成
            if($params['type_money'] == 1){
                $rows[$key]['purchase_total'] = $acct_total[$row['id']] ?? 0;
                if($rows[$key]['purchase_total'] > 0){
                    if($rows[$key]['purchase_total'] > $num){
                        $extra_num = bcdiv($rows[$key]['purchase_total'], $num, 2);
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_d,2) + bcmul($extra_num,$num_big,2);
                    }else if($rows[$key]['purchase_total'] == $num){
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_d,2);
                    }else{
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_lower,2);
                    }
                }else{
                    $rows[$key]['money'] = 0;
                }
            }else{
                // 利润业绩 和 提成
                if(isset($acct_total[$row['id']]) && isset($per_total[$row['id']])){
                    $sum = $acct_total[$row['id']]-$per_total[$row['id']];
                }else{
                    $sum = 0;
                }
                
                $rows[$key]['purchase_total'] =  $sum>0 ? $sum : 0;
                if($rows[$key]['purchase_total'] > 0){
                    if($rows[$key]['purchase_total'] > $num){
                        $extra_num = bcdiv($rows[$key]['purchase_total'], $num, 2);
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_d,2) + bcmul($extra_num,$num_big,2);
                    }else if($rows[$key]['purchase_total'] == $num){
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_d,2);
                    }else{
                        $rows[$key]['money'] = bcmul($rows[$key]['purchase_total'],$num_lower,2);
                    }
                }else{
                    $rows[$key]['money'] = 0;
                }
            }
            

            
        }
        $data= [
            'rows'      => $rows,
            'total'     => $total,
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('获取成功','',$data);
    }
    /**
     * 提成配置
     */
    public function commissionSettingUpdate(){
        $params = $this->request->param();
        $res = json_encode($params['value']);
	    Db::name('config_value')->where('config_key',$params['key'])->update(['value'=>$res]);
        $this->success('操作成功','',$res);
    }
    /**
     * 获取提成配置
     */
    public function commissionSetting(){
        $key = $this->request->param('key');
	    $res = Db::name('config_value')->where('config_key',$key)->value('value');
        $this->success('成功','',json_decode($res,true));
    }
    /**
     * 个人提成配置
     */
    public function commissionUpdate(){
        $params = $this->request->param();
        
        $commission = Db::name('commission')->where(['acct_id' => $params['key'], 'type_money' => $params['type_money']])->find();
        if(empty($commission)){
            $res = Db::name('commission')->insert(array_merge(['acct_id' => $params['key']],$params['value'], ['type_money' => $params['type_money']]));
        }else{
            $res =  Db::name('commission')->where(['acct_id' => $params['key'], 'type_money' => $params['type_money']])->update($params['value']);
        }
        $this->success('操作成功','',$res);
    }
    
}